package com.demo.utils;

import okhttp3.OkHttpClient;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * okhttp 请求工具
 * @author gy
 */
public class OkHttpUtil {

    private static final ConcurrentHashMap<Long, OkHttpClient> CLIENT_MAP = new ConcurrentHashMap<>();

    /**
     * 根据超时时间获取对应的OkHttpClient实例
     * @param timeout 超时时间（秒）
     */
    public static OkHttpClient getClient(long timeout) {
        return CLIENT_MAP.computeIfAbsent(timeout, t ->
                new OkHttpClient.Builder()
                        .connectTimeout(t, TimeUnit.SECONDS)
                        .readTimeout(t, TimeUnit.SECONDS)
                        .writeTimeout(t, TimeUnit.SECONDS)
                        .build()
        );
    }

    /**
     * 获取默认120秒超时的OkHttpClient实例
     */
    public static OkHttpClient getClient() {
        return getClient(120L);
    }
}
